<?php

/**
 * ECTouch Open Source Project
 * ============================================================================
 * Copyright (c) 2012-2014 http://ectouch.cn All rights reserved.
 * ----------------------------------------------------------------------------
 * 文件名称：UserController.class.php
 * ----------------------------------------------------------------------------
 * 功能描述：ECTouch用户中心
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.ectouch.cn/docs/license.txt )
 * ----------------------------------------------------------------------------
 */
/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');
define('WEBIP', 'http://'.$_SERVER["HTTP_HOST"]);
class MshopController extends CommonController {

    protected $user_id;
    protected $mshop_id;//店铺id
    protected $cash_id;//提现账户id
    protected $cat_ids;//商品大类
    protected $action;
    protected $back_act = '';

    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
        // 属性赋值
        $this->user_id = $_SESSION['user_id'];

        $this->action = ACTION_NAME;


        // 验证登录
        $this->check_login();


        $mshop_id=model('Mshop')->getIdByUser_id($this->user_id);
        if($mshop_id)
        {
           $this->mshop_id=$mshop_id; 
        }
        else
        {
             $this->redirect(url('user/mshop_notice'));
             exit();

        }
           
        

        //解冻满足条件的冻结佣金
        // model('Mshop')->unfrozen($this->mshop_id);

        // 用户信息
        $info = model('ClipsBase')->get_user_default($this->user_id);
         // 店铺信息
        $minfo = model('Mshop')->get_info($this->mshop_id);
        $this->cash_id=$minfo['cash_id'];
        $this->cat_ids=$minfo['cat_ids'];
        $minfo['mshop_cnum']=model('Mshop')->count_child_mshop($this->mshop_id);



        //推荐人店铺
        if($minfo['mshop_pid'])
        $puserinfo = model('Mshop')->get_userinfo($minfo['mshop_pid']);
        else
        {$puserinfo['user_name']="无";}

        // 如果是显示页面，对页面进行相应赋值
        assign_template();
        $this->assign('action', $this->action);
        $this->assign('info', $info);

        $minfo['ctime']=date('Y年m月d日',$minfo['ctime']);


        $minfo['sum_cash']=$minfo['sum_profit']+$minfo['frozen_profit'];//实际总佣金

        $minfo['sum_cash']=sprintf('%.2f', $minfo['sum_cash']);
        // $minfo['self_sum_amount']=sprintf('%.2f', $minfo['self_sum_amount']);


        $minfo['cash']=$minfo['sum_profit'];//提现佣金取整


        $this->assign('minfo', $minfo);

        $this->assign('pinfo', $puserinfo);
    }
  
    /**
     * 我的店铺欢迎页
     */
    public function index() {
        // 用户等级
        if ($rank = model('ClipsBase')->get_rank_info()) {
            $this->assign('rank_name', sprintf(L('your_level'), $rank['rank_name']));
        }

         
         $this->assign('mshop_id',$this->mshop_id);
         
         //是否尚未进入
         // $sql = 'select is_into_shop  from '. M()->pre . 'users' . ' where user_id="'.$_SESSION['user_id'].'" limit 1 ';
         // $data_mshop = $this->model->getRow($sql); 
         
         // if($data_mshop['is_into_shop']=='1')
         // {
         //    $user_into['is_into_shop']=2;
         //    $into_where['user_id'] = $_SESSION['user_id'];
         //    $this->model->table('users')
         //                    ->data($user_into)
         //                    ->where($into_where)
         //                    ->update();        
         // }

        //是否启用商品设置      
        $show_shop_go_set=C('show_shop_go_set')?C('show_shop_go_set'):0;
        $this->assign('show_shop_go_set',$show_shop_go_set);
        
        $this->assign('title', '我的店铺管理');
        $this->display('user_mshop.dwt');
    }


     /**
     * 商品设置
     */
     public function go_set()
     {
           //是否启用商品设置      
         $show_shop_go_set=C('show_shop_go_set')?C('show_shop_go_set'):0;
         if(!$show_shop_go_set)
         {
            show_message('您的商品设置功能已失效，如有需要请联系管理员。', '进入我的店', url('mshop/index'), 'info');
         }

         // 修改店铺设置
        if (IS_POST) {
            $cat_ids=$_POST['cat_ids']?$_POST['cat_ids']:"";

            if($cat_ids)
            {
              $sql=" update ".$this->model->pre."mshop set cat_ids='$cat_ids' where mshop_id='$this->mshop_id' ";
              $status=$this->model->query($sql);
                if($status)
                {
                    show_message('您的商品设置已经成功。', '进入我的店', url('mshop/index'), 'info');
                } else 
                {
                    show_message('您的商品设置失败，请重试或联系客服。', L('back_page_up'), '', 'info');
                }           
           }
            else
              show_message('您的商品设置失败。', L('back_page_up'), '', 'info');  

        }

        /**********显示页面-开始*******/
        $this->assign('title','商品设置');
        $category = model('CategoryBase')->get_top_category_for_mshop();


        //是否全选
        $cat_ar=explode(',', $this->cat_ids);
        if(count($cat_ar)==count($category))
        {
             $this->assign('is_select_all','1');
        }

        foreach ($category as $key => &$value) {
            if(in_array($value['id'], $cat_ar))
            {
                $value['selected']=1;
            }
            
        }
        
        
        $this->assign('category', $category);

        // 判断登录方式
        if (model('Users')->is_third_user($_SESSION['user_id'])) {
            $this->assign('is_third', 1);
        }
        $this->display('user_mshop_set.dwt');

        /**********显示页面-结束*******/
        
     }
      /**
     * 佣金提现
     */
     public function go_cash()
     { 
         

         // 提交积分提现
        if (IS_POST) {
              require_once('Wxpay_deliveryController.php'); 
              $Wxpay_delivery=new Wxpay_deliveryController();
              $sql="SELECT m.mshop_id,m.sum_profit,u.openid,u.user_id ".
                  "FROM " . $this->model->pre."mshop as m  ".
                  " left join ". $this->model->pre."users as u on m.mshop_id=u.mshop_id "
                  ." where  m.sum_profit>=1  and u.user_id='$_SESSION[user_id]'";
              $row=$this->model->getRow($sql);
              $status=0;
              if($row)
              {
                 $mshop_id=$row['mshop_id'];
                 $user_id=$row['user_id'];
                 $openid=$row['openid'];
                 $cash_money=intval($row['sum_profit']);
                 $status=$Wxpay_delivery->busSendProfit($mshop_id,$user_id,$openid,$cash_money);            
              }
 
              if($status)
              $sys_mes="提现成功。";
              else
              $sys_mes="提现有误，请重试或者联系客服。";
          
              show_message($sys_mes, L('back_page_up'), '', 'info');  
              exit;

        }
        $sql =  " SELECT p.mch_billno,p.pay_fee,p.status,p.ctime "
                .",u.user_id,u.user_name,u.mobile_phone "
               ."FROM " .$this->model->pre."mshop_pay_log as p"
                ." left join ".$this->model->pre."users  as u on u.user_id=p.user_id "
                ." WHERE u.user_id='$_SESSION[user_id]' "
                ." ORDER BY p.ctime desc "
                ." LIMIT 20 ";
        $list=$this->model->query($sql);
         foreach ($list as $key =>&$value) {
            $value['ctime']=date('Y-m-d H:i:s',$value['ctime']);
            if($value['status']==1)
            {
                $value['status_str']="提现成功";
            }
            else
            {
                $value['status_str']="提现失败";
            }
         }

          $this->assign('list',$list);      
        

       

        /**********显示页面-开始*******/
        $this->assign('title','佣金提现');       

        // 判断登录方式
        if (model('Users')->is_third_user($_SESSION['user_id'])) {
            $this->assign('is_third', 1);
        }
        $this->display('user_mshop_cash.dwt');

        /**********显示页面-结束*******/
        
     }
    
 
      /**
     * 订单销售
     */
     public function order_sales()
     {
        $data=model('Mshop')->get_order_sales($this->mshop_id);

        $this->assign('sales',$data);

        $this->assign('title','订单销售');
        $this->display('user_mshop_order_sales.dwt');
     }
       /**
     * 分销商排行榜
     */
     public function branchshoplist()
     {
         //本人排行榜
         $sql=" select (sum_profit+sum_cash_amount+frozen_profit+lock_profit) as sum_money from "
              .$this->model->pre."mshop where mshop_id=".$this->mshop_id;
         $row=$this->model->getRow($sql);
         $sql="select count(*) as rank from "
              .$this->model->pre."mshop "
              ." where (sum_profit+sum_cash_amount+frozen_profit+lock_profit)>".$row['sum_money'];
        $row2=$this->model->getRow($sql);

        $mrank['sum_money']=round($row['sum_money'],2);
        $mrank['rank']=$row2['rank']+1;
        $this->assign('mrank',$mrank);

         
         //佣金排行榜
         $sql=" select u.user_name,m.mshop_id,(m.sum_profit+m.sum_cash_amount+m.frozen_profit+m.lock_profit) as sum_money from "
              .$this->model->pre."mshop as m"
              ." left join ".$this->model->pre."users as u on m.mshop_id=u.mshop_id "
              .' where u.mshop_id!=0 '
              ." order by (m.sum_profit+m.sum_cash_amount+m.frozen_profit+m.lock_profit) desc limit 20 ";
        $data=$this->model->query($sql);
        
         $this->assign('title','分销商排名');
        foreach ($data as $key => &$value) {
            $value['rank']= $key+1;
            $value['sum_money']=round($value['sum_money'],2);

        }
        $this->assign('list',$data);
        $this->display('user_mshop_branchshop.dwt');
     }
     /**
     * 店铺二维码
     */
     public function shopcode()
     {
        $status=model('Wechat')->check_is_weixin();
        if(!$status)
        {
              show_message('错误,必须在微信下进入。', L('back_page_up'), '', 'info');
            exit();
        }

        $signPackage=model('Wechat')->getSignPackage();

        $newsrow['title']="他人下单，你赚佣金！一起来中服运动吧！一键开店!轻轻松松赚外快！";
        $newsrow['url']=WEBIP.url("index/mshop_notice");
        $newsrow['imgurl']=__URL__."/themes/default/images/wx_open.jpg";

        $newsrow['desc']="一起来中服运动商城开店吧，赚佣金！轻轻松松赚外快！";
        $html_sg='  <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
        <script>
        wx.config({   
        debug: false,
        appId: \''.$signPackage["appId"]. '\',
        timestamp: '.$signPackage["timestamp"].',
        nonceStr: \''.$signPackage["nonceStr"].'\',
        signature: \''. $signPackage["signature"]. '\',
        jsApiList: [
            \'checkJsApi\',
            \'onMenuShareTimeline\',
            \'onMenuShareAppMessage\',
            \'onMenuShareQQ\',
            \'onMenuShareWeibo\',
            \'hideMenuItems\',
            \'showMenuItems\',
            \'hideAllNonBaseMenuItem\',
            \'showAllNonBaseMenuItem\',
            \'translateVoice\',
            \'startRecord\',
            \'stopRecord\',
            \'onRecordEnd\',
            \'playVoice\',
            \'pauseVoice\',
            \'stopVoice\',
            \'uploadVoice\',
            \'downloadVoice\',
            \'chooseImage\',
            \'previewImage\',
            \'uploadImage\',
            \'downloadImage\',
            \'getNetworkType\',
            \'openLocation\',
            \'getLocation\',
            \'hideOptionMenu\',
            \'showOptionMenu\',
            \'closeWindow\',
            \'scanQRCode\',
            \'chooseWXPay\',
            \'openProductSpecificView\',
            \'addCard\',
            \'chooseCard\',
            \'openCard\'
        ]
      });
      wx.checkJsApi({
          jsApiList: [
            \'getNetworkType\',
            \'previewImage\'
          ],
          success: function (res) {
            alert(JSON.stringify(res));
          }
      });
      wx.ready(function () {
        wx.onMenuShareTimeline({
             title: "'.$newsrow['title'].'",
             link: "'.$newsrow['url'].'",
             imgUrl: "'.$newsrow['imgurl'].'",
             trigger: function (res) {
             },
             success: function (res) {       
             },
             cancel: function (res) {            
             },
             fail: function (res) {
             }
        });
        wx.onMenuShareAppMessage({
            title: "",
            desc: "'.$newsrow['desc'].'",
            link: "'.$newsrow['url'].'",
            imgUrl: "'.$newsrow['imgurl'].'",
            trigger: function (res) {
            },
            success: function (res) {
            },
            cancel: function (res) {
            },
            fail: function (res) {
            }
         });
    });
    </script>';
        $this->assign('html_sg',$html_sg);
        $this->assign('title','店铺二维码');
        $img_code=__URL__."/qrcode/qrcode_".$this->mshop_id.".png";

         $code_url=dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/qrcode/qrcode_".$this->mshop_id.".png";
        // if(!file_exists($code_url))
        // {
            /**********二维码生成-开始******************/
            $qrode_url=dirname(dirname(dirname(dirname(__FILE__))))."/phpqrcode.php";
            require_once($qrode_url);
          
            //定义纠错级别
            $errorLevel = "L";
            //定义生成图片宽度和高度;默认为3
            $size = 4;
            //生成网址类型
            $url='http://'.$_SERVER['HTTP_HOST'].url('index/mshop_notice');


            // $url="http://mall.huabintech.com/mobile/index.php?m=default&c=user&a=login&mshopNo=".$this->mshop_id;
             $outfile = 'qrcode/qrcode_'.$this->mshop_id.'.png';//二维码图名称
             $margin=4;//生成图片大小，默认是3
             $saveandprint=false;//是否保存二维码并显示
              // QRcode::png($url,$outfile,$errorLevel,$size,$margin);
             QRcode::png($url, $outfile, $errorLevel, $size);
              /**********二维码生成-结束******************/
        // }

        $this->assign('img_code',$img_code);
        $this->display('user_mshop_shopcode.dwt');
     }

     /**
     * 未登录验证
     */
    private function check_login() {

        // 不需要登录的操作或自己验证是否登录（如ajax处理）的方法
        $without = array(
            'login',
            'register',
            'get_password_phone',
            'get_password_email',
            'get_password_question',
            'pwd_question_name',
            'send_pwd_email',
            'edit_password',
            'check_answer',
            'logout',
            'clear_histroy',
            'add_collection',
            'third_login'
        );
        // 未登录处理
        if (empty($_SESSION['user_id']) && !in_array($this->action, $without)) {
            $url = __HOST__ . $_SERVER['REQUEST_URI'];
            $this->redirect(url('login', array(
                'referer' => urlencode($url)
            )));
            exit();
        }

        // 已经登录，不能访问的方法
        $deny = array(
            'login',
            'register'
        );
        if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0 && in_array($this->action, $deny)) {
            $this->redirect(url('index/index'));
            exit();
        }
    }


}
